package com.agri.service.impl;

import com.agri.dto.CartItemDTO;
import com.agri.entity.CartItem;
import com.agri.entity.Crop;
import com.agri.exception.FinancingException;
import com.agri.mapper.CartItemMapper;
import com.agri.mapper.CropMapper;
import com.agri.result.Result;
import com.agri.service.CartService;
import com.agri.vo.CartItemVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 购物车服务实现类
 * 处理购物车商品的增删改查操作
 *
 * @author Agri-Fin-Sale Team
 * @since 2025-11-05
 */
@Service
@Transactional
public class CartServiceImpl implements CartService {
    @Autowired
    private CartItemMapper cartItemMapper;

    @Autowired
    private CropMapper cropMapper;

    @Override
    public Result<?> addToCart(CartItemDTO cartItemDTO) {
        // 检查商品是否存在且上架
        Crop crop = cropMapper.selectById(cartItemDTO.getCropId());
        if (crop == null) {
            return Result.fail("商品不存在");
        }
        if (crop.getStatus() != 1) {
            return Result.fail("商品已下架");
        }

        // 检查库存
        if (crop.getStock() != null && crop.getStock() < cartItemDTO.getQuantity()) {
            return Result.fail("库存不足");
        }

        // 检查购物车是否已有该商品
        QueryWrapper<CartItem> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", cartItemDTO.getUserId())
               .eq("crop_id", cartItemDTO.getCropId());
        CartItem existingItem = cartItemMapper.selectOne(wrapper);

        if (existingItem != null) {
            // 更新数量
            existingItem.setQuantity(existingItem.getQuantity() + cartItemDTO.getQuantity());
            existingItem.setUpdateTime(new Date());
            cartItemMapper.updateById(existingItem);
            return Result.success("购物车商品数量已更新");
        } else {
            // 新增商品
            CartItem cartItem = new CartItem();
            BeanUtils.copyProperties(cartItemDTO, cartItem);
            cartItem.setUnitPrice(crop.getMarketPrice());
            cartItem.setCreateTime(new Date());
            cartItem.setUpdateTime(new Date());

            int result = cartItemMapper.insert(cartItem);
            if (result > 0) {
                return Result.success("商品已添加到购物车");
            }
            return Result.fail("添加购物车失败");
        }
    }

    @Override
    public Result<?> updateCartItem(Long itemId, Integer quantity) {
        if (quantity <= 0) {
            return removeCartItem(itemId);
        }

        CartItem cartItem = cartItemMapper.selectById(itemId);
        if (cartItem == null) {
            return Result.fail("购物车商品不存在");
        }

        // 检查库存
        Crop crop = cropMapper.selectById(cartItem.getCropId());
        if (crop.getStock() != null && crop.getStock() < quantity) {
            return Result.fail("库存不足");
        }

        cartItem.setQuantity(quantity);
        cartItem.setUpdateTime(new Date());
        int result = cartItemMapper.updateById(cartItem);
        if (result > 0) {
            return Result.success("购物车商品数量已更新");
        }
        return Result.fail("更新购物车商品失败");
    }

    @Override
    public Result<?> removeCartItem(Long itemId) {
        CartItem cartItem = cartItemMapper.selectById(itemId);
        if (cartItem == null) {
            return Result.fail("购物车商品不存在");
        }

        int result = cartItemMapper.deleteById(itemId);
        if (result > 0) {
            return Result.success("商品已从购物车移除");
        }
        return Result.fail("移除购物车商品失败");
    }

    @Override
    public Result<?> clearCart(Long userId) {
        QueryWrapper<CartItem> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);

        int result = cartItemMapper.delete(wrapper);
        return Result.success("购物车已清空，移除了 " + result + " 件商品");
    }

    @Override
    public Result<?> getCartList(Long userId) {
        QueryWrapper<CartItem> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId)
               .orderByDesc("create_time");

        List<CartItem> cartItems = cartItemMapper.selectList(wrapper);

        // 转换为VO对象，包含商品详情
        List<CartItemVO> cartItemVOS = cartItems.stream().map(item -> {
            CartItemVO vo = new CartItemVO();
            BeanUtils.copyProperties(item, vo);

            // 获取商品详情
            Crop crop = cropMapper.selectById(item.getCropId());
            if (crop != null) {
                vo.setCropName(crop.getCropName());
                vo.setCropImage(crop.getImageUrl());
                vo.setMarketPrice(crop.getMarketPrice());
                vo.setStock(crop.getStock());
            }

            // 计算总价
            if (item.getUnitPrice() != null && item.getQuantity() != null) {
                vo.setTotalPrice(item.getUnitPrice().multiply(BigDecimal.valueOf(item.getQuantity())));
            }

            return vo;
        }).collect(Collectors.toList());

        return Result.success(cartItemVOS);
    }

    @Override
    public Result<?> removeCartItems(List<Long> itemIds) {
        if (itemIds == null || itemIds.isEmpty()) {
            return Result.fail("请选择要删除的商品");
        }

        int result = cartItemMapper.deleteBatchIds(itemIds);
        return Result.success("批量删除了 " + result + " 件商品");
    }

    @Override
    public Result<?> getCartCount(Long userId) {
        QueryWrapper<CartItem> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);

        Long count = cartItemMapper.selectCount(wrapper);
        return Result.success(count.intValue());
    }
}